package com.aaa.security;

import com.aaa.jwt.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 拦截请求，判断是否携带的有token
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {



    /**
     * 拦截请求
     * @param httpServletRequest
     * @param httpServletResponse
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token=httpServletRequest.getHeader("token");

        if(token != null){
            //验证token
            Claims claims= JwtTokenUtils.getToken(token);
            //过期
            boolean isExpiration=JwtTokenUtils.isExpiration(claims);
            if(isExpiration) {
                Map auth=JwtTokenUtils.getAuth(claims);
                ArrayList authorities = (ArrayList) auth.get("authorities");
                StringBuffer buffer=new StringBuffer();
                for(int i=0;i<authorities.size();i++){
                    buffer.append(authorities.get(i));
                }

                List<GrantedAuthority> authorityList=AuthorityUtils.commaSeparatedStringToAuthorityList(buffer.toString());
                //配置已经认证
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(auth.get("principal"),auth.get("credentials"),authorityList);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }
}
